package org.logtime.blog.controller.api;

import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.logtime.blog.annotation.AccessLevel;
import org.logtime.blog.annotation.Cache;
import org.logtime.blog.exception.ApiException;
import org.logtime.blog.module.JsonModule;
import org.logtime.blog.pojo.User;
import org.logtime.blog.service.PersistService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @version: 1.0
 * @Author: itmins
 * @Email: itmins@gmail.com
 */
@Controller
@RequestMapping("/users/")
public class UserController {

	@Cache
	@RequestMapping(value = "get.json")
	public JsonModule get(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return JsonModule.getJson(request.getAttribute("accessUser"));
	}

	@Cache(value = Cache.CACHE_CLEAR)
	@RequestMapping(value = "setup.json")
	@AccessLevel(level = AccessLevel.VISTOR_LEVER)
	public JsonModule setup(@RequestParam("name") String name,
			@RequestParam("email") String email,
			@RequestParam("password") String password,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String accessIp = (String) request.getAttribute("accessIp");
		List<User> ulist = persistService.get(User.class).getData();
		if (null != ulist && ulist.size() > 0) {
			throw new ApiException(ApiException.ASK_REQUEST_ERROR_CODE);
		}
		User admin = new User(AccessLevel.ADMIN_LEVER, name, email, password,
				accessIp);
		persistService.save(admin);
		return JsonModule.getJson(admin);
	}

	@Resource
	private PersistService persistService;

	public PersistService getPersistService() {
		return persistService;
	}

	public void setPersistService(PersistService persistService) {
		this.persistService = persistService;
	}
}